﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace BaseTool
{
    /// <summary>
    /// 自定义截图窗体
    /// </summary>
    public partial class ScreenCustomRoiForm : Form
    {
        /// <summary> 截图信息 </summary>
        public static string ErrorMessage = "";

        /// <summary>  </summary>
        private int[] ScreenSize = new int[4] { 0, 0, 0, 0 };
        /// <summary>  </summary>
        private int[] ScreenSizePre = new int[4] { 0, 0, 0, 0 };

        /// <summary>  </summary>
        private System.Drawing.Bitmap BackBit = null;


        /// <summary> 刷新线程 </summary>
        private Thread thdUpdate;
        /// <summary> 退出线程 </summary>
        private bool _isquit = false;
        /// <summary> 鼠标按下 </summary>
        private bool _isMouseDown = false;
        /// <summary> 第一次 按下+移动+释放 </summary>
        private bool _isFirst = true;

        #region 构造
        /// <summary> 构造 </summary>
        public ScreenCustomRoiForm()
        {
            InitializeComponent();
        }
        //加载
        private void frmScreenRoi_Load(object sender, EventArgs e)
        {
            Rectangle r = System.Windows.Forms.Screen.PrimaryScreen.Bounds;

            double scaleX = ScreenControl.ScaleX;
            double scaleY = ScreenControl.ScaleY;
            int width = (int)(r.Width * scaleX);
            int height = (int)(r.Height * scaleY);

            BackBit = new Bitmap(width, height);//截取的大小
            Graphics g = Graphics.FromImage(BackBit);
            g.CopyFromScreen(new System.Drawing.Point(0, 0), new System.Drawing.Point(0, 0), BackBit.Size);

            //窗体最大化，及相关处理
            this.Width = width;
            this.Height = height;
            this.Left = 0;
            this.Top = 0;
            this.TopMost = true;

            ScreenSize[2] = width;
            ScreenSize[3] = height;

            if (scaleX != 1 || scaleY != 1)
                BackBit = Scale(BackBit, 1 / scaleX, 1 / scaleY);
            pictureBox1.bitmap = BackBit;

            thdUpdate = new Thread(Loop);
            thdUpdate.Start();
        }
        //正在关闭
        private void frmScreenRoi_FormClosing(object sender, FormClosingEventArgs e)
        {
            _isquit = true;
            Thread.Sleep(200);
            thdUpdate?.Abort();
        }
        /// <summary>
        /// 缩放图像
        /// </summary>
        /// <param name="bitmap">原始图像</param>
        /// <param name="scaleX">横向缩放(比例)</param>
        /// <param name="scaleY">纵向缩放(比例)</param>
        /// <returns></returns>
        public static Bitmap Scale(Bitmap bitmap, double scaleX, double scaleY)
        {
            if (scaleX < 0) bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX);
            if (scaleY < 0) bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
            return new Bitmap(bitmap, new System.Drawing.Size((int)Math.Abs(bitmap.Width * scaleX), (int)Math.Abs(bitmap.Height * scaleY)));
        }
        #endregion

        /// <summary>
        /// 循环指令
        /// </summary>
        private void Loop()
        {
            while (!_isquit)
            {
                Thread.Sleep(10);
                if (_isMouseDown)
                {
                    _isMouseDown = false;
                    ScreenSizePre[0] = ScreenSize[0];
                    ScreenSizePre[1] = ScreenSize[1];
                    this.Invoke((MethodInvoker)delegate
                    {
                        pictureBox2.Location = new System.Drawing.Point(ScreenSizePre[0], ScreenSizePre[1]);
                        pictureBox2.Visible = true;
                    });
                }
                if (ScreenSize[2] > 0 && ScreenSize[3] > 0)
                {
                    if (ScreenSize[2] != ScreenSizePre[2] || ScreenSize[3] != ScreenSizePre[3])
                    {
                        ScreenSizePre[2] = ScreenSize[2];
                        ScreenSizePre[3] = ScreenSize[3];
                        this.Invoke((MethodInvoker)delegate
                        {
                            pictureBox2.Size = new System.Drawing.Size(ScreenSizePre[2], ScreenSizePre[3]);
                            System.Drawing.Bitmap Bit = BackBit.Clone(new Rectangle(ScreenSizePre[0], ScreenSizePre[1], ScreenSize[2], ScreenSize[3]), BackBit.PixelFormat);
                            pictureBox2.BackgroundImage = Bit;
                        });
                    }
                }
                else
                {
                    this.Invoke((MethodInvoker)delegate
                    {
                        pictureBox2.Size = new System.Drawing.Size(0, 0);
                    });
                }
            }
        }

        #region 画区域
        //鼠标按下
        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (_isFirst)
            {
                _isMouseDown = true;
                ScreenSize[0] = e.X;
                ScreenSize[1] = e.Y;

                //pictureBox2.Location = new Point(e.X, e.Y);
                //pictureBox2.Visible = true;
            }
        }
        //鼠标移动
        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isFirst)
            {
                ScreenSize[2] = e.X - ScreenSize[0];
                ScreenSize[3] = e.Y - ScreenSize[1];

                //if (ScreenSize[2] > 0 && ScreenSize[3] > 0)
                //{
                //    //SuspendLayout();
                //    pictureBox2.Size = new Size(ScreenSize[2], ScreenSize[3]);
                //    Bitmap Bit = BackBit.Clone(new Rectangle(ScreenSize[0], ScreenSize[1], ScreenSize[2], ScreenSize[3]), BackBit.PixelFormat);
                //    pictureBox2.BackgroundImage = Bit;
                //    //ResumeLayout(true);
                //}
                //else
                //{
                //    pictureBox2.Size = new Size(0, 0);
                //}
            }
        }
        //鼠标释放
        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (_isFirst)
            {
                ScreenSize[2] = e.X - ScreenSize[0];
                ScreenSize[3] = e.Y - ScreenSize[1];
                _isFirst = false;

                //ScreenControl.ScreenShot()
                if (ScreenSize[2] > 0 && ScreenSize[3] > 0)
                {
                    try
                    {
                        Bitmap Bit = BackBit.Clone(new Rectangle(ScreenSize[0], ScreenSize[1], ScreenSize[2], ScreenSize[3]), BackBit.PixelFormat);
                        DateTime now = DateTime.Now;
                        string SavePath = $"{PathTool.DataScreenImagePath}{now.ToString("yyyy年MM月dd日")}\\";
                        string FileName = $"Screen_{now.ToString("HHmmss_fff")}.bmp";
                        if (!Directory.Exists(SavePath))
                            Directory.CreateDirectory(SavePath);
                        Bit.Save(SavePath + FileName);
                        ErrorMessage = $"自定义截图成功：保存路径{SavePath}{FileName}";
                    }
                    catch (Exception ex)
                    {
                        ErrorMessage = $"自定义截图异常：{ex.Message}";
                        Log.SaveError(ex);
                    }
                }
                else
                    ErrorMessage = $"自定义截图失败：尺寸为零";
                this.Close();
            }
        }

        private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right) this.Close();
        }
        private void pictureBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            this.Close();
        }
        private void frmScreenRoi_KeyPress(object sender, KeyPressEventArgs e)
        {
            this.Close();
        }
        #endregion
    }
}
